using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Flurl.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace COVIDInquire
{

    public partial class _Index : Page
    {


        protected async void Page_Load(object sender, EventArgs e)
        {

            string jsonText = await "https://api.covid19api.com/countries".GetStringAsync();
            //string jsonText = "[{\"Country\":\"Barbados\",\"Slug\":\"barbados\",\"ISO2\":\"BB\"},]";
            JArray ja = (JArray)JsonConvert.DeserializeObject(jsonText);
            // RootObject rb = JsonConvert.DeserializeObject<RootObject>(jsonText);
            var sortja = new JArray(ja.OrderBy(obj => (string)obj["Country"]));  //Order by Alphbet
            
            for (int i = 0; i < sortja.Count; i++)
            {
                if (sortja[i]["Country"].ToString() == "Taiwan, Republic of China")
                    drop1.Items.Add(new ListItem("Taiwan, Province of China", sortja[i]["Slug"].ToString()));  // One China Policy
                else drop1.Items.Add(new ListItem(sortja[i]["Country"].ToString(), sortja[i]["Slug"].ToString()));
            }
        }

        protected void submit(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;
            DataByCountry(drop1.SelectedItem.Value);
            mess.Text = "Untill "+ dt.ToString("yyyy-MM-dd")  ;
            Country_name.Text = drop1.SelectedItem.Text;
        }

        protected async void DataByCountry(string Slug)
        {
            string api = "https://api.covid19api.com/total/country/" + Slug + "/status/confirmed";
            string jsonText = await api.GetStringAsync();
            writelog(api);  // save api,time,and IP address in txt file
            JArray data = (JArray)JsonConvert.DeserializeObject(jsonText);
            string total;
            if (data.Count == 0)   // Some countries or regions haven't data.
            {
                total = "No data";
                total_case.Text = "Total COVID-19 cases:" + total;
                lastday_case.Text = "";
                compare.Text = "";
            }
            else
            {
                total = data[data.Count - 1]["Cases"].ToString();
                total_case.Text = "Total COVID-19 cases:" + total;
                double yesterday = double.Parse(data[data.Count - 1]["Cases"].ToString()) - double.Parse(data[data.Count - 2]["Cases"].ToString());
                lastday_case.Text = "Today increase:" + yesterday.ToString();
                double day_before_yesterday = double.Parse(data[data.Count - 2]["Cases"].ToString()) - double.Parse(data[data.Count - 3]["Cases"].ToString());
                compare.Text = "Compare to the previous day:" + (yesterday / day_before_yesterday * 100).ToString("F4") + "%";
            }
        }

        protected void writelog(string api)
        {
            DateTime dt = DateTime.Now;
            using (StreamWriter sw = new StreamWriter("log.txt",true))
            {
                sw.WriteLine(dt.ToString());//time
                sw.WriteLine(GetClientIPv4Address());//IP address
                sw.WriteLine(api);//call to API
                sw.WriteLine("");//blank line
            }
        }
        //IP addresses Function by https://blog.csdn.net/a992935798/article/details/50518512
        string GetClientIPv4Address()
        {
            string ipv4 = String.Empty;

            foreach (IPAddress ip in Dns.GetHostAddresses(GetClientIP()))
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    ipv4 = ip.ToString();
                    break;
                }
            }

            if (ipv4 != String.Empty)
            {
                return ipv4;
            }

            foreach (IPAddress ip in Dns.GetHostEntry(GetClientIP()).AddressList)
            //foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    ipv4 = ip.ToString();
                    break;
                }
            }

            return ipv4;
        }
            string GetClientIP()
        {
            if (null == HttpContext.Current.Request.ServerVariables["HTTP_VIA"])
            {
                return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            else
            {
                return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            }
        }
    }
}